<!--
 * @Descripttion: 用印表单
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-06-02 17:59:37
 * @LastEditTime: 2022-12-07 16:12:47
 * @Param {Void}
 * @Example <use-seal></use-seal>
 * @FilePath: \cscec-pms-admin\src\views\Legal\branchContract\otherTypesContract\components\UseSeal.vue
-->
<template>
  <a-spin :spinning="loading">
    <!-- 基本信息 -->
    <a-card :bordered="false">
      <title-name title="基本信息" />
      <custom-form
        ref="form0"
        :is-validate="true"
        :edit-model="''"
        :rules="rules[0]"
        :form="form[0]"
        :form-list="formOption[0]"
        @getItem="changeDate"
      />
    </a-card>
    <!-- 基本信息 -->
    <!-- 评审人员 -->
    <a-card :bordered="false">
      <title-name title="评审人员" />
      <custom-form
        ref="form1"
        :is-validate="true"
        :edit-model="''"
        :rules="rules[1]"
        :form="form[1]"
        :form-list="formOption[1]"
      />
    </a-card>
    <!-- 评审人员 -->
    <!-- 附件 -->
    <a-card :bordered="false">
      <title-name title="附件" />
      <UploadTableNew
        ref="uploadTable"
        :disabled="type==='detail'"
        :mode="file.mode"
        :init-file-list="file.fileList"
        :need-page="file.needPage"
        :business-code="file.businessCode"
      />
    </a-card>
    <!-- 附件 -->
    <!-- 底部按钮 -->
    <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
      <base-print-button
        v-if="isDisabled&&!$route.query.taskDefKey"
        type="primary"
        :before-print-fn="handlePrint"
      />
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        class="ml12"
        type="default"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <!-- 底部按钮 -->
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </a-spin>
</template>
<script>
import SelectUndertaking from '@/components/Select/SelectUndertaking'
import otherTypesContract from '@/api/legal/branchContract/otherTypesContract'
import Moment from 'moment'
import BasePrintButton from '@/components/BasePrintButton'
export default {
  name: 'UseSeal',
  props: {
    type: {
      type: String,
      require: true
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  components: {
    BasePrintButton
  },
  data() {
    return {
      // 接口响应代码
      resCode: 200,
      // 页面加载
      loading: false,
      //表单
      form: [
        {
          applicantUnit: '中国建筑第八工程局有限公司西南分公司',
          contractName: void 0,
          otherParty: void 0,
          amount: 0,
          sealType: '其他类',
          sealCode: void 0,
          contractNum: void 0,
          projectManagerId: void 0,
          projectManagerPhone: void 0,
          processPass: void 0,
          auditOpinion: void 0,
          auditOptions: void 0,
          sponsorId: void 0,
          sponsorPhone: void 0,
          applyTime: void 0,
          auditProgram: void 0,
          approval: void 0,
          jointSignature: void 0,
          remark: void 0
        },
        {
          competenBusinessId: void 0,
          contractLawId: void 0,
          businessLeaderId: void 0
        }
      ],
      // 表单索引
      index: [0, 1],
      // 登录人信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      // 附件
      file: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: 'add',
        // 上传文件的业务编码
        businessCode: 'LCM08',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: []
      },
      // 公司id
      orgId: '53085e2c9f1f4685801ef31994f57c49',
      // 打印loading
      printLoading: false,
      // 表单提交loading
      submitLoading: false,
      // 字典
      dicts: {
        WHETHER: [
          {
            label: '否',
            value: '0'
          },
          {
            label: '是',
            value: '1'
          }
        ],
        AUDIT_OPINION: [
          {
            label: '无审核意见',
            value: '0'
          },
          {
            label: '已按审核意见采纳',
            value: '1'
          },
          {
            label: '未采纳',
            value: '2'
          }
        ]
      },
        //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 表单禁用
    isDisabled() {
      return this.type === 'detail'
    },
    // 表单配置
    formOption() {
      return [
        // 基本信息
        [
          {
            label: '申请单位',
            keyName: 'applicantUnit',
            type: 'BaseInput',
            disabled: true,
            span: 24
          },
          {
            label: '合同名称',
            keyName: 'contractName',
            type: 'BaseInput',
            disabled: true,
            span: 24
          },
          {
            label: '合同对方',
            keyName: 'otherParty',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '合同价(万元)',
            keyName: 'amount',
            type: 'BaseInputNumber',
            disabled: true
          },
          {
            label: '合同类型',
            keyName: 'sealType',
            type: 'BaseInputNumber',
            disabled: true
          },
          {
            label: '合同编号',
            keyName: 'sealCode',
            type: 'BaseInput',
            disabled: this.isDisabled
          },
          {
            label: '合同份数',
            keyName: 'contractNum',
            type: 'BaseInputNumber',
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请输入', trigger: 'change' }]
          },
          {
            label: '项目经理',
            keyName: 'projectManagerId',
            type: SelectUndertaking,
            placeholder: '请选择',
            attrs: {
              allowClear: true,
              orgId: this.userInfo.id
            },
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '项目经理联系电话',
            keyName: 'projectManagerPhone',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '本合同是否按规定流程经过评审通过',
            keyName: 'processPass',
            type: 'a-select',
            data: this.dicts.WHETHER,
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '本合同审核意见处理情况',
            keyName: 'auditOpinion',
            type: 'a-select',
            data: this.dicts.AUDIT_OPINION,
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '本合同审核意见处理情况',
            keyName: 'auditOptions',
            type: 'BaseTextarea',
            disabled: this.isDisabled,
            attrs: {
              maxLength: 1000
            },
            autoSize: { minRows: 3, maxRows: 7 },
            span: 24
          },
          {
            label: '经办责任人',
            keyName: 'sponsorId',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '经办责任人联系电话',
            keyName: 'sponsorPhone',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '申请时间',
            keyName: 'applyTime',
            type: 'BaseInput',
            disabled: true
          },
          {
            label: '是否经过会同审核程序',
            keyName: 'auditProgram',
            type: 'a-select',
            data: this.dicts.WHETHER,
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '是否经过授权合同批准人批准',
            keyName: 'approval',
            type: 'a-select',
            data: this.dicts.WHETHER,
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '是否经过合同联签',
            keyName: 'jointSignature',
            type: 'a-select',
            data: this.dicts.WHETHER,
            disabled: this.isDisabled,
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '其他',
            keyName: 'remark',
            type: 'BaseTextarea',
            disabled: this.isDisabled,
            attrs: {
              maxLength: 1000
            },
            autoSize: { minRows: 3, maxRows: 7 },
            span: 24
          }
        ],
        // 评审人员
        [
          {
            label: '公司业务主管部门负责人',
            keyName: 'competenBusinessId',
            type: SelectUndertaking,
            disabled: this.isDisabled,
            placeholder: '请选择',
            attrs: {
              allowClear: true,
              orgId: this.orgId,
              isInclude: true,
              isDefault: false,
              requestParams: { and: true, orgType: '2' }
            },
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '公司合约法务部经办负责人',
            keyName: 'contractLawId',
            type: SelectUndertaking,
            disabled: this.isDisabled,
            placeholder: '请选择',
            attrs: {
              allowClear: true,
              orgId: this.orgId,
              isInclude: true,
              isDefault: false,
              requestParams: { and: true, orgType: '2' }
            },
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          },
          {
            label: '公司业务分管领导',
            keyName: 'businessLeaderId',
            type: SelectUndertaking,
            disabled: this.isDisabled,
            placeholder: '请选择',
            attrs: {
              allowClear: true,
              orgId: this.orgId,
              isInclude: true,
              isDefault: false,
              requestParams: { and: true, orgType: '2' }
            },
            rules: [{ required: true, message: '请选择', trigger: 'change' }]
          }
        ]
      ]
    },
    // 校验
    rules() {
      const arr = []
      this.formOption.forEach((el) => {
        let obj = {}
        el.forEach((item) => {
          if (item.rules) {
            obj[item.keyName] = item.rules
          }
        })
        arr.push(obj)
      })
      return arr
    }
  },
 async created() {
    this.getDate()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('legal_other_review_apply_new')
  },
  methods: {
    /**
     * @description: 获取带出数据
     * @param {Void}
     * @return {Void}
     */
    async getDate() {
      this.loading = true
      try {
        // 经办责任人
        this.form[0].sponsorId = this.userInfo.name
        // 经办责任人联系电话
        this.form[0].sponsorPhone = this.userInfo.username
        // 申请时间
        this.form[0].applyTime = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        // 审批时
        if (this.$route.query.taskDefKey) {
          await this.getFromInfo()
          await this.getBaseInfo(this.form[0].id)
        } else if(this.$route.query.businessType== '1113'){   //意见征询
           await this.getFromInfo()
        }else{
          await this.getBaseInfo()
          await this.getFromInfo()
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    /**
     * @description: 获取基本信息
     * @param {Void}
     * @return {Void}
     */
    async getBaseInfo(id = this.$route.query.id) {
      const { data } = await otherTypesContract.findListByMainId({ id })
      // id
      this.form[0].id = data.id
      // 写入基本信息
      Object.keys(this.form[0]).forEach((item) => {
        this.form[0][item] = data[item] || this.form[0][item]
      })
      return Promise.resolve()
    },
    /**
     * @description: 获取回显数据
     * @param {Void}
     * @return {Void}
     */
    async getFromInfo(id = this.$route.query.id) {
      // 回显数据
      if (this.type !== 'add') {
        let obj = void 0
        if (this.$route.query.taskDefKey || this.$route.query.businessType== '1113') {
          const { data } = await otherTypesContract.findSealByBusinessId({ sealBusinessId: id })
          // id
          this.form[0].id = data.baseId
          obj = data
        } else {
          const { data } = await otherTypesContract.findSealByBaseId({ id })
          // id
          this.form[0].id = data.baseId
          obj = data
        }
        // 写入对应的form
        this.form.forEach((el, index) => {
          if (this.index.includes(index)) {
            Object.keys(el).forEach((item) => {
              el[item] = obj[item] || el[item]
            })
          }
        })
        this.form[0].projectManagerId = {
          key: obj?.projectManagerId?.keyId,
          label: obj?.projectManagerId?.label
        }
        this.form[1].competenBusinessId = {
          key: obj?.competenBusinessId?.keyId,
          label: obj?.competenBusinessId?.label
        }
        this.form[1].contractLawId = {
          key: obj?.contractLawId?.keyId,
          label: obj?.contractLawId?.label
        }
        this.form[1].businessLeaderId = {
          key: obj?.businessLeaderId?.keyId,
          label: obj?.businessLeaderId?.label
        }
        this.file.fileList = obj.fileInfoVos || []
      }
      return Promise.resolve()
    },
    /**
     * @description: 打印
     * @param {Void}
     * @return {Void}
     */
    async handlePrint() {
      const {
        data: { content }
      } = await otherTypesContract.sealPrint({ baseId: this.$route.query.id })
      return content
    },
    /**
     * @description: 提交表单
     * @param {String} type 提交类型
     * @return {Void}
     */
    async handleSubmit(type) {
      this.setProcessConfig = null;
      const obj = this.form[1]
      const base = {
        baseId: this.$route.query.id,
        fileInfoVos: this.file.fileList,
        competenBusinessId: obj?.competenBusinessId?.key
          ? {
              keyId: obj.competenBusinessId.key,
              label: obj.competenBusinessId.label
            }
          : null,
        contractLawId: obj?.contractLawId?.key
          ? {
              keyId: obj.contractLawId.key,
              label: obj.contractLawId.label
            }
          : null,
        businessLeaderId: obj?.businessLeaderId?.key
          ? {
              keyId: obj.businessLeaderId.key,
              label: obj.businessLeaderId.label
            }
          : null,
        projectManagerId: this.form[0]?.projectManagerId?.key
          ? {
              keyId: this.form[0].projectManagerId.key,
              label: this.form[0].projectManagerId.label
            }
          : null
      }
      // 保存草稿
      if (type === 'DRAFT') {
        base.sealAuditStatus = 'DRAFT'
        this.submitLoading = true
        const data = Object.assign({}, ...this.form, base)
        otherTypesContract
          .editSeal(data)
          .then(({ code }) => {
            if (code === this.resCode) {
              this.$message.success('保存成功')
            } else {
              this.$message.warning('保存失败')
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      }
      // 提交
      if (type === 'SUBMITTED') {
        const validate = this.index.map((el) => {
          let isValidate = false
          this.$refs['form' + el].validate((valid) => {
            if (valid) {
              isValidate = true
            }  else {
              this.$message.warning("请填写完所有必填项信息")
            }
          })
          return isValidate
        })
        if (validate.indexOf(false) < 0) {
          this.submitApprovalConfirm(this.processConfig, async (flag)=>{
            if(!flag) {
              this.submitLoading = false
              return
            }
          try {
            // 保存
            base.sealAuditStatus = 'SUBMITTED'
            const data = Object.assign({}, ...this.form, base)
            this.submitLoading = true
            const { code } = await otherTypesContract.editSeal(data)
            if (code === this.resCode) {
              // 提交
              const res = await otherTypesContract.sealSubmit({
                auditStatusEnum: 'SUBMITTED',
                baseId: this.form[0].id
              })
              if (res.code === this.resCode) {
                this.$message.success('提交成功')
                this.businessId = res.data.sealBusinessId;
                this.setProcessConfig = this.processConfig;
                // this.handleClose()
              } else {
                this.$message.warning('提交失败')
              }
            } else {
              this.$message.warning('提交失败')
            }
          } catch (error) {
            console.log(error)
          } finally {
            this.submitLoading = false
          }
          })
        }
      }
    },
    /**
     * @description: 关闭
     * @param {Void}
     * @return {Void}
     */
    handleClose() {
      this.$close()
    },
    /**
     * @description: 表单选人回调
     * @param {String} e 字段名
     * @param {Object} v 值
     * @return {Void}
     */
    changeDate(e, v) {
      if (e === 'projectManagerId') {
        this.form[0].projectManagerPhone = v.phone
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
